﻿/* $RCSFile: RadTreeComboPages.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/ADNCRM.Core/UI/WebControls/RadTreeComboPages.cs $
 * $log$
 * Revision 19 2011/02/22 01:23:08  christian.surieux
 *   V4 Migration 22/2/11
 * Revision 19 2011/02/22 01:22:19  christian.surieux
 *   V4 Migration 22/2/11
 * Revision 6 2010/08/06 19:56:30  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Reflection;
using System.Collections;
using System.IO;
using System.Data;
using System.Web;
using System.Text;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Globalization;

using AddonNice.Core;
using AddonNice.UI;
using AddonNice.UI.WebControls;
using AddonNice.UI.DataTypes;
using AddonNice.Configuration;
using AddonNice.Diagnostics;
using AddonNice.Helpers;
using AddonNice.Settings;
using AddonNice.Security;

using Telerik.Web.UI;

using Trace2    =   System.Diagnostics.Trace;

namespace AddonNice.UI.WebControls
{
	#region TraceSwitch for all WebControls
	public class RadTreeComboPagesTrace : ADNTraceSwitch
	{
		static public ADNTraceSwitch Sw = new ADNTraceSwitch("RadTreeComboPagesTrace", "Trace Switch for RadTreeComboPages");
	}
	#endregion TraceSwitch for all RadTreeComboPages

	[ToolboxData("<{0}:RadTreeComboPages runat='server'></{0}:RadTreeComboPages>")]
	public class RadTreeComboPages : RadComboBox
	{
		protected class PageComboTemplate : ITemplate
		{
			public int PortalID                 =   -1;
			public string Skin                  =   string.Empty;
			public string selVal                =   string.Empty;
			protected RadComboBoxItem ComboItem =   null;
			public RadTreeView RadTree1         =   null;
			public HtmlGenericControl div1      =   null;

			PagesDB pagesDB                     =   new PagesDB();

			public PageComboTemplate(int pID,string wskin)
			{
				if (RadTreeComboPagesTrace.Sw.TraceVerbose)
					Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadTreeComboPages PageComboTemplate Ctor PortalID: {0}, Skin: {1}", pID, wskin), RadTreeComboPagesTrace.Sw.Info);
				PortalID    =   pID;
				if ( wskin != string.Empty)
					Skin    =   wskin;

			}

			protected virtual void InstallDataBinder()
			{
				RadTree1.DataBinding += new EventHandler(RadTree1_DataBinding);
			}


			// Normally triggered by the DataBind of the containing Page
			public void InstantiateIn(Control container)
			{
				if (RadTreeComboPagesTrace.Sw.TraceVerbose)
					Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadTreeComboPages PageComboTemplate InstantiateIn BEG container: {0}", container), RadTreeComboPagesTrace.Sw.Info);
				if ( container is RadComboBoxItem )
					ComboItem                       =   container as RadComboBoxItem; //save container
				else
				{
					const string msg  =   "[E]RadTreeComboPages PageComboTemplate InstantiateIn container is not RadComboBoxItem";
					if (RadTreeComboPagesTrace.Sw.TraceError)
						Trace2.WriteLine(msg, RadTreeComboPagesTrace.Sw.Info);
					throw new Exception(msg);
				}
				div1                            =   new HtmlGenericControl(StStr.Div);
				div1.ID                         =   "div1";
				RadTree1                        =   new RadTreeView();
				RadTree1.ID                     =   string.Format("RadTree_{0}",((RadTreeComboPages)ComboItem.ComboBoxParent).ClientID);
				RadTree1.ClientIDMode           =   ClientIDMode.Predictable;
				RadTree1.Height                 =   ((RadTreeComboPages)ComboItem.ComboBoxParent).Height;
				RadTree1.OnClientNodeClicking   =   ((RadTreeComboPages)ComboItem.ComboBoxParent).makeScriptName();
				if ( Skin != string.Empty )
					RadTree1.Skin               =   Skin;
				RadTree1.AllowNodeEditing       =   false;
				RadTree1.EnableDragAndDrop      =   false;
				RadTree1.EnableDragAndDropBetweenNodes = false;
				RadTree1.MultipleSelect         =   false;
				InstallDataBinder();
				div1.Controls.Add(RadTree1);
				container.Controls.Add(div1);
				/*
				// attaching the StopPropagation javascript to onclick for the div
				string script                   =   string.Format("document.getElementById('{0}').onclick = StopPropagation;",div1.ClientID);
				if ( container.Page is ADNPage )
						((ADNPage)container.Page).RegisterADNStartupScript(typeof(Page), string.Format("attachHandler_{0}",div1.ClientID), script, true);
				else    container.Page.ClientScript.RegisterStartupScript(typeof(Page), string.Format("attachHandler_{0}",div1.ClientID), script, true);
				 * */
				if (RadTreeComboPagesTrace.Sw.TraceVerbose)
					Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadTreeComboPages PageComboTemplate InstantiateIn END container: {0}", container), RadTreeComboPagesTrace.Sw.Info);
			}
			
			/// <summary>
			/// Bind to portal pages, creating the existing hierarchy
			/// </summary>
			void RadTree1_DataBinding(object sender, EventArgs e)
			{
				if (RadTreeComboPagesTrace.Sw.TraceVerbose)
					Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadTreeComboPages PageComboTemplate RadTree1_DataBinding BEG sender: {0}", sender), RadTreeComboPagesTrace.Sw.Info);
				RadTreeView RadTree1            =   (RadTreeView)sender;
				RadTreeComboPages CbPage        =   (RadTreeComboPages)ComboItem.ComboBoxParent;
				bool SelectFirst                =   CbPage.SelectFirst && string.IsNullOrEmpty(selVal);
				bool SelectSel                  =   !string.IsNullOrEmpty(selVal);
				
				SqlDataReader dr                =   null;
				try
				{
					dr                          =   pagesDB.GetAllPortalPages(PortalID);
					while (dr.Read())
					{
						ADNPageFlags Flag       =    ADNPageFlags.Normal;
						// We skip pages not Ok for menus, i.e. system pages
						if ( dr[StStr.DBPageLayout] != DBNull.Value )
							Flag                =   ((ADNPageFlags)dr[StStr.DBPageLayout]);
						if ( ( CbPage.ExcludeFlags != ADNPageFlags.Normal ) && 
							( Flag != ADNPageFlags.Normal ) && 
							( ( CbPage.ExcludeFlags & Flag) != ADNPageFlags.Normal ) )
							continue;
						int tabId               =   (int)dr[StStr.DBPageID];
						int parentTabId         =   Convert.IsDBNull(dr[StStr.DBParentPageID]) ? 0 : (int)dr[StStr.DBParentPageID];
						RadTreeNode nd          =   new RadTreeNode((string)dr[StStr.DBPageKeyPhrase], tabId.ToString());
						RadTreeNode nd1         =   RadTree1.FindNodeByValue(parentTabId.ToString());
						nd.AllowDrag            =   false;
						nd.AllowDrop            =   false;
						nd.AllowEdit            =   false;
						nd.Expanded             =   true;
						if ( ( SelectSel && nd.Value == selVal) || SelectFirst )
						{
							SelectFirst         =   false;
							nd.Selected         =   true;
							if (RadTreeComboPagesTrace.Sw.TraceVerbose)
								Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadTreeComboPages PageComboTemplate RadTree1_DataBinding selected nd.Text: {0}, ComboItem != null: {1}", nd.Text,ComboItem != null ), RadTreeComboPagesTrace.Sw.Info);
							if (RadTreeComboPagesTrace.Sw.TraceVerbose)
								Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadTreeComboPages PageComboTemplate RadTree1_DataBinding Combo Ok nd.Text: {0}.", nd.Text ), RadTreeComboPagesTrace.Sw.Info);
							ComboItem.Text      =   nd.Text;
							ComboItem.Value     =   nd.Value;
							ComboItem.Selected  =   true;
						}
						if ( nd1 != null )
						{
							if (RadTreeComboPagesTrace.Sw.TraceVerbose)
								Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadTreeComboPages PageComboTemplate RadTree1_DataBinding Adding {0} to {1}", nd.Text, nd1.Text), RadTreeComboPagesTrace.Sw.Info);
							nd1.Nodes.Add(nd);
						}
						else
						{
							if (RadTreeComboPagesTrace.Sw.TraceVerbose)
								Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadTreeComboPages PageComboTemplate RadTree1_DataBinding Adding {0} to root", nd.Text), RadTreeComboPagesTrace.Sw.Info);
							RadTree1.Nodes.Add(nd);
						}
					}
					// Should we skip pages under Admin 
					if (RadTreeComboPagesTrace.Sw.TraceVerbose)
						Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadTreeComboPages PageComboTemplate RadTree1_DataBinding IncludeAdmin: {0}", CbPage.IncludeAdmin), RadTreeComboPagesTrace.Sw.Info);
					if (!CbPage.IncludeAdmin)
					{
						RadTreeNode nd          =   RadTree1.Nodes.FindNodeByValue(StStr.strPageAdminID);
						if (RadTreeComboPagesTrace.Sw.TraceVerbose)
							Trace2.WriteLine("[V]RadTreeComboPages PageComboTemplate removing Admin Page", RadTreeComboPagesTrace.Sw.Info);
						if (nd != null)
							RadTree1.Nodes.Remove(nd);
					}
					// Should we skip some Page
					if (RadTreeComboPagesTrace.Sw.TraceVerbose)
						Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadTreeComboPages PageComboTemplate RadTree1_DataBinding SkipList: [{0}]", CbPage.SkipList.ToString()), RadTreeComboPagesTrace.Sw.Info);
					if (!string.IsNullOrEmpty(CbPage.SkipList))
					{
						string[] pageID         =   CbPage.SkipList.Split(new char[]{';'},StringSplitOptions.RemoveEmptyEntries);
						for (int i=0; i < pageID.Length ; i++ )
						{
							if ( string.IsNullOrEmpty(pageID[i] ) )
								continue;
							RadTreeNode nd      =   RadTree1.FindNodeByValue(pageID[i]);
							if (nd != null)
							{
								if (RadTreeComboPagesTrace.Sw.TraceVerbose)
									Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadTreeComboPages PageComboTemplate RadTree1_DataBinding Removing PageID: {0}", pageID[i]), RadTreeComboPagesTrace.Sw.Info);
								nd.Owner.Nodes.Remove(nd);
							}
						}
					}
					// Should we include the Default Welcome
					if ( CbPage.IncludeDefaultWelcome )
					{
						string DefWelcName      =   LocalizeHelper.Localize("SITE_WELCOME_PAGE","Site Welcome Page");
						RadTreeNode nd          =   new RadTreeNode(DefWelcName, StStr.parentDBIdNotSet.ToString());
						if ( ( SelectSel && nd.Value == selVal) || SelectFirst )
						{
							nd.Selected         =   true;
							ComboItem.Text      =   nd.Text;
							ComboItem.Value     =   nd.Value;
							ComboItem.Selected  =   true;
						}
						RadTree1.Nodes.Insert(0,nd);                        
					}

					if (RadTreeComboPagesTrace.Sw.TraceVerbose)
						Trace2.WriteLine("[V]RadTreeComboPages PageComboTemplate RadTree1_DataBinding Ok", RadTreeComboPagesTrace.Sw.Info);
				}
				catch (Exception ex)
				{
					if (RadTreeComboPagesTrace.Sw.TraceError)
						Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]RadTreeComboPages PageComboTemplate RadTree1_DataBinding ex:{0}", ex), RadTreeComboPagesTrace.Sw.Info);
					throw;
				}
				finally
				{
					if (dr != null)
						dr.Close();
				}
			}

		}

		bool _IncludeDefaultWelcome    =   false;
		/// <summary>
		/// Include the 'default Welcome Page' in tree, ie '0'
		/// Default False
		/// </summary>
		[DefaultValue("False")]
		[PersistenceMode(PersistenceMode.Attribute)]
		public bool IncludeDefaultWelcome
		{
			get
			{
				return _IncludeDefaultWelcome;
			}
			set
			{
				_IncludeDefaultWelcome = value;
			}
		}

		bool _SelectFirst    =   true;
		/// <summary>
		/// Select the firts element in treeview if no selectedItem set
		/// Default True
		/// </summary>
		[DefaultValue("True")]
		[PersistenceMode(PersistenceMode.Attribute)]
		public bool SelectFirst
		{
			get
			{
				return _SelectFirst;
			}
			set
			{
				_SelectFirst = value;
			}
		}

		ADNPageFlags _ExcludeFlags   =   ADNPageFlags.Normal;
		public ADNPageFlags ExcludeFlags

		{
			get
			{
				return _ExcludeFlags;
			}
			set
			{
				_ExcludeFlags = value;
			}
		}

		bool _IncludeAdmin          =   true;

		/// <summary>
		/// Should we include the Admin elements (Pages or Modules) in the treeview
		/// Default True
		/// </summary>
		[DefaultValue("True")]
		[PersistenceMode(PersistenceMode.Attribute)]
		public bool IncludeAdmin
		{
			get
			{
				return _IncludeAdmin;
			}
			set
			{
				_IncludeAdmin = value;
			}
		}

		string _SkipList    =   string.Empty;
		/// <summary>
		/// Must contain a list of Id to skip in the treeview, values separted by ';'
		/// Each page is referenced by is PageID
		/// Each module is referenced by is DefModuleID
		/// Default to string.Empty
		/// </summary>
		[DefaultValue("")]
		[PersistenceMode(PersistenceMode.Attribute)]
		public string SkipList
		{
			get
			{
				return _SkipList;
			}
			set
			{
				_SkipList = value;
			}
		}

		string _UnSelectables    =   string.Empty;
		/// <summary>
		/// Must contain a list of Id that would not be selectable in the treeview, values separted by ';'
		/// Default to string.Empty
		/// </summary>
		[DefaultValue("")]
		[PersistenceMode(PersistenceMode.Attribute)]
		public string UnSelectables
		{
			get
			{
				return _UnSelectables;
			}
			set
			{
				_UnSelectables = value;
			}
		}

		string _TreeViewSkin    =   string.Empty;
		[DefaultValue("Web20")]
		[PersistenceMode(PersistenceMode.Attribute)]
		public string TreeViewSkin
		{
			get
			{
				return _TreeViewSkin;
			}
			set
			{
				_TreeViewSkin = value;
			}
		}

		public override bool Visible
		{
			get
			{
				return base.Visible;
			}
			set
			{
				if (RadTreeComboPagesTrace.Sw.TraceVerbose)
					Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadTreeComboPages Visible SET value: {0}.",value),RadTreeComboPagesTrace.Sw.Info);
				base.Visible        =   value;
				if ( ItemTemplate != null )
				{
					if ( ((PageComboTemplate)ItemTemplate).RadTree1 != null )
						((PageComboTemplate)ItemTemplate).RadTree1.Visible  =   value;
				}
			}
		}
		
		public int PortalID =   -1;

		/// <summary>
		/// Represents a combobox filled with a hierarchical treeview of portal pages
		/// </summary>
		public RadTreeComboPages()
		{
			//AllowCustomText    =   true; // Telerik pb v2008 515 Text doesn't display on start
			// design mode
			if ( HttpContext.Current == null )
				return;
			PortalSettings portalSettings = (PortalSettings)HttpContext.Current.Items[StStr.strPortalSettings];
			PortalID    =   portalSettings.PortalID;
		}

		protected virtual string[] UnSelectable
		{
			get
			{
				if (string.IsNullOrEmpty(UnSelectables))
				{
					return new string[0];
				}
				string[] tb = UnSelectables.Split(new char[]{';'},StringSplitOptions.RemoveEmptyEntries);
				return tb;
			}
		}

		protected virtual string LoadScript(string nm,string scriptname,string gscript,string param2)
		{
			string vscriptPath          =   Config.PortalScriptsPath+"/"+scriptname;
			string scriptPath           =   MapPathSecure(vscriptPath);
			string src                  =   string.Empty;
			TextReader rd               =    null;
			try
			{
				// Try to read directories from public theme path
				bool exist              =   File.Exists(scriptPath);
				if ( RadTreeComboPagesTrace.Sw.TraceVerbose )
					Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadTreeComboPages LoadScript scriptPath: {0}, exists: {1}", scriptPath,exist ),RadTreeComboPagesTrace.Sw.Info);
				if ( exist)
				{
					rd                  =   new StreamReader(scriptPath);
					string fmt          =   rd.ReadToEnd();
					if ( RadTreeComboPagesTrace.Sw.TraceVerbose )
						Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadTreeComboPages LoadScript fmt: [{0}]", fmt),RadTreeComboPagesTrace.Sw.Info);
					src                 =   string.Format(fmt,new object[]{nm,ClientID,gscript,param2});
					if ( RadTreeComboPagesTrace.Sw.TraceVerbose )
						Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadTreeComboPages LoadScript src: [{0}]", src),RadTreeComboPagesTrace.Sw.Info);
				}
			}
			catch (Exception ex)
			{
				if ( RadTreeComboPagesTrace.Sw.TraceError )
					Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]RadTreeComboPages LoadScript ex: {0}", ex),RadTreeComboPagesTrace.Sw.Info);
				throw;
			}
			finally
			{
				if (rd != null)
					rd.Close();
			}
			if (RadTreeComboPagesTrace.Sw.TraceVerbose)
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadTreeComboPages LoadScript script: [{0}].",src),RadTreeComboPagesTrace.Sw.Info);
			return src;
		}

		protected virtual string makeScript(string nm)
		{
			if ( RadTreeComboPagesTrace.Sw.TraceVerbose )
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadTreeComboPages makeScript BEG nm: [{0}]", nm),RadTreeComboPagesTrace.Sw.Info);
			string src                  =   string.Empty;
			try
			{
				// build global script text inserted as param[2]
				StringBuilder sb    =     new StringBuilder();
				sb.Append("var node = args.get_node();");
				for (int i=0; i < UnSelectable.Length ; i++ )
					sb.AppendFormat("if (node.get_value() == '{0}') return;",UnSelectable[i]);
				string gscript      =   sb.ToString();
				src                 =   LoadScript(nm,"RadTreeCombo.ajs",gscript,string.Empty);
				if ( RadTreeComboPagesTrace.Sw.TraceVerbose )
					Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadTreeComboPages makeScript src: [{0}]", src),RadTreeComboPagesTrace.Sw.Info);
				if ( string.IsNullOrEmpty(src) )
				{
					sb              =     new StringBuilder();
					sb.AppendFormat("function {0}(sender, args)\n{{",nm);
					sb.Append(gscript);
					sb.AppendFormat("var comboBox = $find('{0}');\n",this.ClientID);
					sb.Append("var cboItem=comboBox.get_items().getItem(0);\n");
					sb.Append("comboBox.trackChanges();\n");
					sb.Append("cboItem.set_value(node.get_value());\n");
					sb.Append("cboItem.set_text(node.get_text());\n");
					sb.Append("cboItem.select();\n");
					sb.Append("comboBox.commitChanges();\n");
					sb.Append("comboBox.hideDropDown();\n");
					sb.Append("comboBox.attachDropDown();}\n");

					src             =   sb.ToString();
				}
			}
			catch (Exception ex)
			{
				if ( RadTreeComboPagesTrace.Sw.TraceError )
					Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]RadTreeComboPages makeScript ex: {0}", ex),RadTreeComboPagesTrace.Sw.Info);
				throw;
			}
			if (RadTreeComboPagesTrace.Sw.TraceVerbose)
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadTreeComboPages makeScript script: [{0}].",src),RadTreeComboPagesTrace.Sw.Info);
			return src;
		}
		
		protected virtual string makeOnClientDropDownOpened(string nm,string treeName)
		{
			string src                  =   string.Empty;
			try
			{
				src                     =   LoadScript(nm,"ClientDropDownOpened.ajs",string.Empty,treeName);
				if ( RadTreeComboPagesTrace.Sw.TraceVerbose )
					Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadTreeComboPages makeOnClientDropDownOpened src: [{0}]", src),RadTreeComboPagesTrace.Sw.Info);
				if ( string.IsNullOrEmpty(src) )
				{
					StringBuilder sb    =   new StringBuilder();
					sb.AppendFormat("function {0}(sender, eventArgs)\n{{",nm);
					sb.AppendFormat("var tree = sender.get_items().getItem(0).findControl('{0}');\n",treeName);
					sb.Append("var selectedNode = tree.get_selectedNode();\nif (selectedNode) selectedNode.scrollIntoView();\n}");
					src                 =   sb.ToString();
				}
			}
			catch (Exception ex)
			{
				if ( RadTreeComboPagesTrace.Sw.TraceError )
					Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]RadTreeComboPages makeOnClientDropDownOpened ex: {0}", ex),RadTreeComboPagesTrace.Sw.Info);
				throw;
			}
			if (RadTreeComboPagesTrace.Sw.TraceVerbose)
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadTreeComboPages makeOnClientDropDownOpened script={0}.",src),RadTreeComboPagesTrace.Sw.Info);
			return src;
		}
		
		protected virtual string makeStopPropagation()
		{
			string src                  =   string.Empty;
			try
			{
				src                     =   LoadScript(string.Empty,"StopPropagation.ajs",string.Empty,string.Empty);
				if ( RadTreeComboPagesTrace.Sw.TraceVerbose )
					Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadTreeComboPages makeStopPropagation src: [{0}]", src),RadTreeComboPagesTrace.Sw.Info);
				if ( string.IsNullOrEmpty(src) )
				{
					StringBuilder sb    =   new StringBuilder();
					sb.Append("function StopPropagation(e)\n{");
					sb.Append("if (!e)\n{e = window.event;}\n e.cancelBubble = true;if (e.stopPropagation)\n{e.stopPropagation();}\n}\n");
					src          =   sb.ToString();
				}
			}
			catch (Exception ex)
			{
				if ( RadTreeComboPagesTrace.Sw.TraceError )
					Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]RadTreeComboPages makeStopPropagation ex: {0}", ex),RadTreeComboPagesTrace.Sw.Info);
				throw;
			}
			if (RadTreeComboPagesTrace.Sw.TraceVerbose)
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadTreeComboPages makeStopPropagation script={0}.",src),RadTreeComboPagesTrace.Sw.Info);
			return src;
		}

		protected override bool LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection)
		{
			if (RadTreeComboPagesTrace.Sw.TraceVerbose)
				Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture, "[V]RadTreeComboPages LoadPostData BEG postDataKey: {0}", postDataKey), RadTreeComboPagesTrace.Sw.Info);
			bool ret    =   base.LoadPostData(postDataKey, postCollection);
			if (RadTreeComboPagesTrace.Sw.TraceVerbose)
				Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture, "[V]RadTreeComboPages LoadPostData END ret: {0}", ret), RadTreeComboPagesTrace.Sw.Info);
			return ret;
		}
		
		override protected void OnInit(EventArgs e)
		{
			if (RadTreeComboPagesTrace.Sw.TraceVerbose)
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadTreeComboPages OnInit BEG IsPostBack: {0}", Page.IsPostBack), RadTreeComboPagesTrace.Sw.Info);
			InitializeComponent();
			base.OnInit(e);
			if (RadTreeComboPagesTrace.Sw.TraceVerbose)
				Trace2.WriteLine("[V]RadTreeComboPages OnInit END.", RadTreeComboPagesTrace.Sw.Info);
		}
		protected virtual string makeScriptName()
		{
			return string.Format("nodeClicking_{0}", ClientID);
		}

		protected virtual string makeDropDownOpenedName()
		{
			return string.Format("OnClientDropDownOpenedHandler_{0}",ClientID);
		}

		protected override void OnPreRender(EventArgs e)
		{
			if (RadTreeComboPagesTrace.Sw.TraceVerbose)
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadTreeComboPages OnPreRender BEG IsPostBack: {0}, Visible: {1}", Page.IsPostBack,Visible), RadTreeComboPagesTrace.Sw.Info);

			// attaching the StopPropagation javascript to onclick for the div
			HtmlGenericControl div1     =   (HtmlGenericControl )((PageComboTemplate)ItemTemplate).div1;
			string script               =   string.Format("document.getElementById('{0}').onclick = StopPropagation;",div1.ClientID);
			((ADNPage)Page).RegisterADNStartupScript(typeof(Page), string.Format("attachHandler_{0}",div1.ClientID), script, true);
			string nm                   =   makeScriptName();
			( (ADNPage)Page ).RegisterADNClientScriptBlock(GetType(),nm,makeScript(nm),true);
			( (ADNPage)Page ).RegisterADNClientScriptBlock(GetType(),"StopPropagation",makeStopPropagation(),true);
			// new in 1.527 to open treeview and scroll to selected value
			OnClientDropDownOpened      =   makeDropDownOpenedName();            
			string treeName             =   string.Format("RadTree_{0}",ClientID);
			( (ADNPage)Page ).RegisterADNClientScriptBlock(GetType(),OnClientDropDownOpened,makeOnClientDropDownOpened(OnClientDropDownOpened,treeName),true);
			base.OnPreRender(e);
			if (RadTreeComboPagesTrace.Sw.TraceVerbose)
				Trace2.WriteLine("[V]RadTreeComboPages OnPreRender END.", RadTreeComboPagesTrace.Sw.Info);
		}

		protected virtual void InitItemTemplate()
		{
			ItemTemplate    =  new PageComboTemplate(PortalID,TreeViewSkin);
		}

		
		protected virtual void InitializeComponent()
		{
			if (RadTreeComboPagesTrace.Sw.TraceVerbose)
				Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture, "[V]RadTreeComboPages InitializeComponent BEG EnableViewState: {0}, Page.IsPostBack: {1}.", EnableViewState, Page.IsPostBack), RadTreeComboPagesTrace.Sw.Info);
			InitItemTemplate();
			if ( !EnableViewState || !Page.IsPostBack)
			{
				if (RadTreeComboPagesTrace.Sw.TraceVerbose)
					Trace2.WriteLine("[V]RadTreeComboPages InitializeComponent Adding first RadComboItem BEG.", RadTreeComboPagesTrace.Sw.Info);
				RadComboBoxItem rdcbItem    =   new RadComboBoxItem();
				// bug telerik v 515 rdcbItem.Selected   =   true;
				Items.Add(rdcbItem);
				if (RadTreeComboPagesTrace.Sw.TraceVerbose)
					Trace2.WriteLine("[V]RadTreeComboPages InitializeComponent Adding first RadComboItem END.", RadTreeComboPagesTrace.Sw.Info);
			}
			if (RadTreeComboPagesTrace.Sw.TraceVerbose)
				Trace2.WriteLine("[V]RadTreeComboPages InitializeComponent END.", RadTreeComboPagesTrace.Sw.Info);
		}

		/// <summary>
		/// SET Must be call before DataBind
		/// </summary>
		public virtual string SelectedTreeViewValue
		{
			get
			{
				if (ItemTemplate != null)
				{
					return ((PageComboTemplate)ItemTemplate).selVal;
				}
				return null;
			}
			set
			{
				if (ItemTemplate != null)
				{
					((PageComboTemplate)ItemTemplate).selVal = value;
					if (RadTreeComboPagesTrace.Sw.TraceVerbose)
						Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadTreeComboPages SelectedTreeViewValue SET value: {0}", value), RadTreeComboPagesTrace.Sw.Info);
				}
			}
		}
	}
}
